<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-02 19:42:06
 * @LastEditTime: 2023-06-28 13:49:49
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Repositories;

use App\Models\MarketOffer;

/**
 * 报价
 * @property MarketOffer $model 
 * @author sunkaiyuan
 */
class MarketOfferRepository extends Repositories
    {
    protected $relation_models = ['material','department', 'status', 'creator', 'updator'];

    public function boot(MarketOffer $model)
        {
        $this->model = $model;
        }

    /**
     * 匹配通用报价单
     * @param mixed $material_id
     * @param mixed $type_id
     * @param mixed $department_id
     * @return mixed
     * @author sunkaiyuan
     */
    public function mate($material_id, $type_id, $department_id = null)
        {
        $data = $this->whereMaterial_id($material_id)
            ->whereType_id($type_id)
            ->where("department_id", "=", $department_id ?? auth()->user()->department_id)
            ->where("billdate", "<=", date("Y-m-d H:i:s"))
            ->orderBy("billdate", "desc")
            ->first();
        if ($data) {
            return $data;
            }
        //区域报价没有，就找通用的
        return $this->whereMaterial_id($material_id)
            ->whereType_id($type_id)
            ->where("department_id", "=", "0")
            ->where("billdate", "<=", date("Y-m-d H:i:s"))
            ->orderBy("billdate", "desc")
            ->first();
        }
    }